package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Component
public class URLPicutreUpload extends PictureUploadTemplate {
    @Override
    protected String getMainName(Object file) {
        return FileUtil.mainName(file.toString());
    }

    @Override
    public void checkPacture(Object file) throws MalformedURLException {
        String url = (String) file;
        //参数校验
        if(StrUtil.isBlank(url)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"url不能为空");
        }
        //校验url格式
        new URL(url);
        //校验url协议
        if(!url.startsWith("http") || !url.startsWith("https")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"url格式错误");
        }
        //校验url是否存在
        HttpResponse response = HttpUtil.createRequest(Method.HEAD, url).execute();
        //not normal return
        if(response.getStatus() != HttpStatus.HTTP_OK){
            return;
        }
        //校验文本格式
        String header = response.header("Content-Type");
        List<String> ALLOWS_CONTENT_TYPES = Arrays.asList("image/jpeg","image/png");
        if(!ALLOWS_CONTENT_TYPES.contains(header)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片格式错误");
        }
        //校验文件大小
        String filesize = response.header("Conent-Length");
        long length = Long.parseLong(filesize);
        final long RuleSize = 1024*1024;
        if(length > 2*RuleSize){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小不能大于2M");
        }
    }

    @Override
    public void OjbectToFile(Object file, File tempFile) throws IOException {
        HttpUtil.downloadFile(file.toString(),tempFile);
    }
}
